import React, { useEffect, useState } from 'react';
import {
  Box,
  Button,
  Card,
  CardContent,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  IconButton,
  Paper,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TextField,
  Typography,
  useTheme,
  useMediaQuery,
  Alert,
  Snackbar,
} from '@mui/material';
import {
  Add as AddIcon,
  Delete as DeleteIcon,
  Edit as EditIcon,
} from '@mui/icons-material';
import axios from 'axios';

const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:3001/api';

interface Device {
  deviceId: string;
  name: string;
  type: string;
  status: string;
  lastHeartbeat: string;
}

interface DeviceManagementProps {
  userId?: string;
}

const DeviceManagement: React.FC<DeviceManagementProps> = ({ userId }) => {
  const [devices, setDevices] = useState<Device[]>([]);
  const [openDialog, setOpenDialog] = useState(false);
  const [selectedDevice, setSelectedDevice] = useState<Device | null>(null);
  const [newDevice, setNewDevice] = useState({
    deviceId: '',
    name: '',
    type: '',
    password: '',
  });
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down('sm'));

  const fetchDevices = async () => {
    try {
      const token = localStorage.getItem('token');
      const response = await axios.get(`${API_URL}/devices`, {
        headers: {
          Authorization: `Bearer ${token}`
        }
      });
      setDevices(response.data);
    } catch (error: any) {
      setError('获取设备列表失败：' + (error.response?.data?.message || error.message));
    }
  };

  useEffect(() => {
    fetchDevices();
  }, []);

  const handleCreateDevice = async () => {
    try {
      // 验证必填字段
      if (!newDevice.deviceId || !newDevice.name || !newDevice.type || !newDevice.password) {
        setError('请填写所有必填字段');
        return;
      }

      const token = localStorage.getItem('token');
      await axios.post(
        `${API_URL}/devices`,
        newDevice,
        {
          headers: {
            Authorization: `Bearer ${token}`
          }
        }
      );
      setSuccess('设备创建成功');
      setOpenDialog(false);
      setNewDevice({ deviceId: '', name: '', type: '', password: '' });
      fetchDevices();
    } catch (error: any) {
      setError('创建设备失败：' + (error.response?.data?.message || error.message));
    }
  };

  const handleDeleteDevice = async (deviceId: string) => {
    try {
      const token = localStorage.getItem('token');
      await axios.delete(`${API_URL}/devices/${deviceId}`, {
        headers: {
          Authorization: `Bearer ${token}`
        }
      });
      setSuccess('设备删除成功');
      fetchDevices();
    } catch (error: any) {
      setError('删除设备失败：' + (error.response?.data?.message || error.message));
    }
  };

  const handleUpdateDevice = async (deviceId: string, updates: Partial<Device>) => {
    try {
      const token = localStorage.getItem('token');
      await axios.put(
        `${API_URL}/devices/${deviceId}`,
        updates,
        {
          headers: {
            Authorization: `Bearer ${token}`
          }
        }
      );
      setSuccess('设备更新成功');
      fetchDevices();
    } catch (error: any) {
      setError('更新设备失败：' + (error.response?.data?.message || error.message));
    }
  };

  return (
    <Box>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
        <Typography variant={isMobile ? "h5" : "h4"} gutterBottom>
          设备管理
        </Typography>
        <Button
          variant="contained"
          startIcon={<AddIcon />}
          onClick={() => setOpenDialog(true)}
        >
          添加设备
        </Button>
      </Box>

      <TableContainer component={Paper} elevation={0}>
        <Table size={isMobile ? "small" : "medium"}>
          <TableHead>
            <TableRow>
              <TableCell>设备名称</TableCell>
              <TableCell>类型</TableCell>
              {!isMobile && <TableCell>状态</TableCell>}
              {!isMobile && <TableCell>最后心跳</TableCell>}
              <TableCell align="right">操作</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {devices.map((device) => (
              <TableRow key={device.deviceId}>
                <TableCell>{device.name}</TableCell>
                <TableCell>{device.type}</TableCell>
                {!isMobile && <TableCell>{device.status}</TableCell>}
                {!isMobile && <TableCell>{new Date(device.lastHeartbeat).toLocaleString()}</TableCell>}
                <TableCell align="right">
                  <IconButton
                    color="primary"
                    onClick={() => setSelectedDevice(device)}
                    size={isMobile ? "small" : "medium"}
                    title="编辑设备"
                  >
                    <EditIcon />
                  </IconButton>
                  <IconButton
                    color="error"
                    onClick={() => handleDeleteDevice(device.deviceId)}
                    size={isMobile ? "small" : "medium"}
                    title="删除设备"
                  >
                    <DeleteIcon />
                  </IconButton>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </TableContainer>

      {/* 添加设备对话框 */}
      <Dialog 
        open={openDialog} 
        onClose={() => setOpenDialog(false)} 
        maxWidth="sm" 
        fullWidth
        PaperProps={{
          sx: {
            m: isMobile ? 0 : 2,
            borderRadius: isMobile ? 0 : 1,
          }
        }}
      >
        <DialogTitle sx={{ p: isMobile ? 1 : 2 }}>添加新设备</DialogTitle>
        <DialogContent sx={{ p: isMobile ? 1 : 2 }}>
          <Box sx={{ display: 'flex', flexDirection: 'column', gap: isMobile ? 1 : 2, pt: isMobile ? 1 : 2 }}>
            <TextField
              label="设备ID"
              value={newDevice.deviceId}
              onChange={(e) => setNewDevice({ ...newDevice, deviceId: e.target.value })}
              fullWidth
              size={isMobile ? "small" : "medium"}
              required
            />
            <TextField
              label="设备名称"
              value={newDevice.name}
              onChange={(e) => setNewDevice({ ...newDevice, name: e.target.value })}
              fullWidth
              size={isMobile ? "small" : "medium"}
              required
            />
            <TextField
              label="设备类型"
              value={newDevice.type}
              onChange={(e) => setNewDevice({ ...newDevice, type: e.target.value })}
              fullWidth
              size={isMobile ? "small" : "medium"}
              required
            />
            <TextField
              label="设备密码"
              type="password"
              value={newDevice.password}
              onChange={(e) => setNewDevice({ ...newDevice, password: e.target.value })}
              fullWidth
              size={isMobile ? "small" : "medium"}
              required
            />
          </Box>
        </DialogContent>
        <DialogActions sx={{ p: isMobile ? 1 : 2 }}>
          <Button onClick={() => setOpenDialog(false)} size={isMobile ? "small" : "medium"}>取消</Button>
          <Button onClick={handleCreateDevice} variant="contained" size={isMobile ? "small" : "medium"}>
            添加
          </Button>
        </DialogActions>
      </Dialog>

      {/* 提示消息 */}
      <Snackbar
        open={!!error}
        autoHideDuration={6000}
        onClose={() => setError(null)}
        anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
      >
        <Alert severity="error" onClose={() => setError(null)}>
          {error}
        </Alert>
      </Snackbar>

      <Snackbar
        open={!!success}
        autoHideDuration={6000}
        onClose={() => setSuccess(null)}
        anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
      >
        <Alert severity="success" onClose={() => setSuccess(null)}>
          {success}
        </Alert>
      </Snackbar>
    </Box>
  );
};

export default DeviceManagement; 